var mongoose = require('mongoose');
var config = require('../config/config.js');
// console.log(config.mongooseConfig);
// mongoose.connect(config.mongooseConfig);

/**
 * [connect description]  Connect to mongodb
 * @return {[type]} [description]
 */
var connect = function() {
	var options = {
		server: {
			socketOptions: {
				keepAlive: 1 // 保持长连接
			}
		}
	};
	mongoose.connect(config.mongooseConfig, options);
};

// start connect...
connect();

mongoose.connection.on('open', function() {
	console.info('mongodb opened...');
});

// Error handler
mongoose.connection.on('error', function(err) {
	console.error('mongodb exception：%s', err);
});

var count = 0;
// Reconnect when closed
mongoose.connection.on('disconnected', function() {
	console.warn('mongodb disconnected... reconneting %s seconds ', count);

	count++;
	if (count <= 5) {
		setTimeout(connect, 3000);
	} else {
		process.exit(1);
	}
});

exports.mongoose = mongoose;